package backend.ro.msg.gillardon.persistence.orientdb;

import java.time.LocalDateTime;
import java.util.List;

import backend.ro.msg.gillardon.entities.Article;
import backend.ro.msg.gillardon.persistence.ApiInterface;

import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;

public class ObjectApi implements ApiInterface {

  //  private static final Logger LOG = Logger.getLogger(ObjectApi.class);
  private final OObjectDatabaseTx db;

  public ObjectApi() {
    this.db = new OObjectDatabaseTx(DATABASE_URL);

  }

  public OObjectDatabaseTx getConnection() {
    return this.db;
  }

  @Override
  public void createRecord() {
    this.db.open("msg", "msgGillardon");
    // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
    this.db.getEntityManager().registerEntityClasses("backend.ro.msg.gillardon.entities");

    // CREATE A NEW PROXIED OBJECT AND FILL IT
    Article article = this.db.newInstance(Article.class);
    article.setTitle("newTitle");
    article.setContent("random content");
    //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime timerPoint = LocalDateTime.now();
    //LOG.debug(LocalDateTime.parse(timerPoint.format(formatter), formatter));
    article.setWhenPublished(timerPoint);

    // SAVE THE RECORD: THE DATABASE WILL SERIALIZE THE OBJECT AND GIVE THE PROXIED INSTANCE
    article = this.db.save(article);

    this.db.close();
  }

  @Override
  public void updateRecord() {
    this.db.open("msg", "msgGillardon");
    // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
    this.db.getEntityManager().registerEntityClasses("backend.ro.msg.gillardon.entities");
    String titleToBeUpdated = "newTitle";
    List<Article> result = this.db.query(
      new OSQLSynchQuery<Article>("select * from Article where title='" + titleToBeUpdated + "'"));
    for (Article article : result) {
      article.setTitle("Title objectApi");
      this.db.save(article);
    }
    this.db.close();
  }

  @Override
  public void deleteRecord() {
    this.db.open("msg", "msgGillardon");
    // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
    this.db.getEntityManager().registerEntityClasses("backend.ro.msg.gillardon.entities");
    String titleToBeDeleted = "Title objectApi";
    List<Article> result = this.db.query(
      new OSQLSynchQuery<Article>("select * from Article where title='" + titleToBeDeleted + "'"));
    for (Article article : result) {
      this.db.delete(article);
    }
    this.db.close();

  }
}
